<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\controller\property\property\basic;

use think\App;
use app\controller\property\Base;
use app\validate\property\unit\PropertyUnitValidate;
use app\common\repositories\room\RoomBasicRepository;
use app\common\repositories\property\basic\PropertyUnitRepository;
use app\common\repositories\property\basic\PropertyBasicRepository;

class PropertyUnit extends Base
{
    protected $repository;

    public function __construct(App $app, PropertyUnitRepository $repository)
    {
        parent::__construct($app);

        $this->repository = $repository;
    }

    /**
     * 职权部门列表
     * @return string|\think\response\Json
     * @throws \Exception
     *
     * @author Amos
     * 2024-01-18 21:32
     */
    public function list()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'property_id' => '',
                'keywords' => '',
            ]);
            [$page, $limit] = $this->getPage();
            $res = $this->repository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        } else {
            return $this->fetch('property/unit/list', [
                'addAuth' => property_auth('propertyGroupAdd'),
                'editAuth' => property_auth('propertyGroupEdit'),
                'delAuth' => property_auth('propertyGroupDel'),
                'detailAuth' => property_auth('propertyGroupDetail'),
            ]);
        }
    }

    /**
     * 添加职权部门
     * @return string|\think\response\Json|\think\response\View
     * @throws \Exception
     *
     * @author Amos
     * 2024-01-18 17:47
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'unit_name' => '',
                'pid' => '',
                'is_show' => '',
                'remark' => '',
            ]);
            $param['pid'] = (int)$param['pid'];
            validate(PropertyUnitValidate::class)->scene('add')->check($param);
            if ($this->repository->unitNameExists($this->request->propertyId, $param['unit_name'], $param['pid'])) {
                return $this->error($param['unit_name'] . '已存在');
            }
            try {
                $res = $this->repository->addInfo($param, $this->request->propertyId, $this->request->userId);
                if ($res) {
                    return $this->success('添加成功');
                } else {
                    return $this->error('添加失败');
                }
            } catch (\Exception $e) {
                exception_log('添加楼栋单元', $e);
                return $this->error('网络错误');
            }
        } else {
            $topData = $this->repository->getSearch([])
                ->where('pid', 0)
                ->where('is_show', 1)
                ->where('property_id', $this->request->propertyId)
                ->field('id,unit_name')
                ->select()->toArray();
            return $this->fetch('property/unit/add', [
                'topData' => $topData
            ]);
        }
    }


    /**
     * 编辑
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-01-17 22:15
     */
    public function edit()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $info = $this->repository->get($id);
        if (!$info) {
            return $this->error('信息错误');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'unit_name' => '',
                'pid' => '',
                'is_show' => '',
                'remark' => '',
            ]);
            validate(PropertyUnitValidate::class)->scene('edit')->check($param);
            try {
                $res = $this->repository->editInfo($info, $param, $this->request->userId);
                if ($res) {
                    return $this->success('修改成功');
                } else {
                    return $this->error('修改失败');
                }
            } catch (\Exception $e) {
                exception_log('编辑楼栋单元失败', $e);
                return $this->error('网络错误');
            }
        } else {
            return $this->fetch('property/unit/edit', [
                'info' => $info,
            ]);

        }
    }

    /**
     * 删除职权部门
     * @return string|\think\response\Json|\think\response\View
     *
     * @author Amos
     * 2024-01-17 22:15
     */
    public function del()
    {
        validate(PropertyUnitValidate::class)->scene('del')->check($this->request->param());
        $id = (int)$this->request->param('id');
        $info = $this->repository->get($id);
        if (!$info) {
            return $this->error('信息错误');
        }
        try {
            if ($this->repository->hasChild($id)) {
                return $this->error('该分类存在下级分类，请先处理下级分类');
            }
            $roomBasicRepository = app()->make(RoomBasicRepository::class);
            $rentCount = $roomBasicRepository->getSearch(['unit_id' => $info['id']])
                ->whereIn('status', ['2,3,4'])
                ->count();
            if ($rentCount > 0) {
                return $this->error('当前单元存在出租或预约、预定的房屋，禁止删除');
            }
            $data = $this->repository->deleteInfo($info, $this->request->userId);
            if ($data) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败');
            }
        } catch (\Exception $e) {
            exception_log('删除楼栋单元失败', $e);
            return $this->error('网络错误');
        }
    }


    public function detail()
    {
        $id = (int)$this->request->param('id');
        if ($id <= 0) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($id);
        if ($info['id'] <= 0) {
            return $this->error('信息不存在');
        }
        return $this->fetch('property/unit/detail', [
            'info' => $info,
        ]);
    }

}